package com.ujs.listnode.code.RemoveNode;

import com.ujs.listnode.code.ListNode;
import com.ujs.listnode.code.NodeInit;

/**
 * @author zhangshihao
 * @create 2023-09-26 15:33
 */
public class RemoveElements {
    public static void main(String[] args) {
        RemoveElements removeElements = new RemoveElements();
        ListNode head = NodeInit.getNode();
        ListNode listNode = removeElements.removeElements3(head, 6);

        while (listNode != null) {
            System.out.print(listNode.getVal() + " ");
            listNode = listNode.getNext();
        }
    }

    /**
     * 添加虚拟节点
     *
     * @param head
     * @param val
     * @return
     */
    public ListNode removeElements(ListNode head, int val) {
        if (head == null) {
            return head;
        }
        // 因为删除可能涉及到头结点，所以设置虚拟节点，统一操作
        ListNode dummy = new ListNode(-1, head);
        ListNode pre = dummy;
        ListNode cur = head;
        while (cur != null) {
            if (cur.val == val) {
                pre.next = cur.next;
            } else {
                pre = cur;
            }
            cur = cur.next;
        }
        return dummy.next;
    }

    /**
     * 直接操作，需要对head特殊处理
     *
     * @param head
     * @param val
     * @return
     */
    public ListNode removeElements2(ListNode head, int val) {
        if (head == null) {
            return null;
        }
        // 排除掉head的值等于val的情况
        while (head != null && head.val == val) {
            head = head.next;
        }
        ListNode pre = head;
        ListNode cur = head.next;
        while (cur != null) {
            if (cur.val == val) {
                pre.next = cur.next;
            } else {
                pre = cur;
            }
            cur = cur.next;
        }
        return head;
    }

    public ListNode removeElements3(ListNode head, int val) {
        while (head != null && head.val == val) {
            head = head.next;
        }
        ListNode cur = head;
        while (cur != null) {
            while (cur.next != null && cur.next.val == val) {
                cur.next = cur.next.next;
            }
            cur = cur.next;
        }
        return head;
    }
}
